<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\traits;


trait ModelTrait
{
    public static function get($where)
    {
        if(!is_array($where)){
            return self::find($where);
        }else{
            return self::where($where)->find();
        }
    }

    public static function all($function){
        $query = self::newQuery();
        $function($query);
        return $query->select();
    }


    /**
     * 获取一条数据
     *
     * @param $where
     * @param $field
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getOne($where, $field = [])
    {
        return self::where($where)->field($field)->find();
    }

    /*
     * 获取所有数据
     * */
    public static function getAll($where=[], $order = [], $field = [],$limit=0){
        return self::where($where)->field($field)->order($order)->limit($limit)->select();
    }


    /**
     * 获取某一个字段数据
     *
     * @param $where
     * @param $field
     * @return mixed
     */
    public static function getFieldValue($where, $field, $default = null)
    {
        return self::where($where)->value($field, $default);
    }


    /**
     * 获取分页数据(关联查询)
     *
     * @param $condition
     * @return \think\Paginator
     */
    public static function getPageAll($condition)
    {
        $query = self::where($condition['where']);

        if (! empty($condition['field'])) {
            $query->field($condition['field']);
        }
        $per_page = null;
        if (empty($condition['paginate']['list_rows'])) {
            $condition['paginate']['list_rows'] = 15;
            //unset($condition['paginate']['list_rows']);
        }

        if (! empty($condition['order'])) {
            $query->order($condition['order']);
        }
        if (! empty($condition['with'])) {
            $query->with($condition['with']);
        }

        //print_r($condition['paginate']);die();

        $page_data = $query->paginate($condition['paginate'],false);

        return $page_data;
    }

    /**
     * 获取查询数据
     *
     * @param array $condition
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getQueryAll($condition = [])
    {
        $where = empty($condition['where']) ? [] : $condition['where'];
        $query = self::where($where);
        if (! empty($condition['field'])) {
            $query->field($condition['field']);
        }
        if (! empty($condition['order'])) {
            $query->order($condition['order']);
        }
        if (! empty($condition['with'])) {
            $query->with($condition['with']);
        }

        return $query->select();
    }


    /**
     * 获取 数量
     *
     * @param        $where
     * @param string $field
     * @return int|string
     */
    public static function getCount($where, $field = '*')
    {
        return self::where($where)->count($field);
    }

    /**
     * 插入一条数据
     *
     * @param       $data
     * @param array $field
     * @return false|int
     */
    public static function insertOne($data, $field = [])
    {
        return self::allowField($field)->save($data);
    }

    /**
     * 添加多条数据
     * @param $group
     * @param bool $replace
     * @return mixed
     */
    public static function setAll($group, $replace = false)
    {
        return self::insertAll($group,$replace);
    }


    /**
     * 更新一条数据
     *
     * @param $data
     * @param $where
     * @param $field
     * @return false|int
     */
    public static function updateOne($data, $where, $allowField = [])
    {
        return self::update($data,$where,$allowField);
    }

    /**
     * 更新多条数据
     *
     * @param $data
     * @param $where
     * @param $field
     * @return false|int
     */
    public static function updateAll($data)
    {
        $self = new self();
        return $self->saveAll($data);
    }

    /**
     * 修改一条数据
     * @param $data
     * @param $id
     * @param $field
     * @return bool $type 返回成功失败
     */
    public static function edit($data,$id,$field = null)
    {
        $model = new self;
        if(!$field) $field = $model->getPk();
        $res = $model->update($data,[$field=>$id]);
        if(isset($res->result))
            return 0 < $res->result;
        else if(isset($res['data']['result']))
            return  0 < $res['data']['result'];
        else
            return false !== $res;
    }


    /**
     * 查询一条数据是否存在
     * @param $map
     * @param string $field
     * @return bool 是否存在
     */
    public static function be($map, $field = '')
    {
        $model = (new self);
        if(!is_array($map) && empty($field)) $field = $model->getPk();
        $map = !is_array($map) ? [$field=>$map] : $map;
        return 0 < $model->where($map)->count();
    }

    /**
     * 根据主键删除一条数据
     * @param $id
     * @return bool $type 返回成功失败
     */
    public static function del($id)
    {
        return false !== self::destroy($id);
    }


    /**
     * 根据where条件删除一条数据
     * @param $id
     * @return bool $type 返回成功失败
     */
    public static function delByWhere($where=[])
    {
        if(empty($where)){
            return false;
        }
        return false !== self::where($where)->delete();
    }

    /**
     * 分页
     * @param null $model 模型
     * @param null $eachFn 处理结果函数
     * @param array $params 分页参数
     * @param int $limit 分页数
     * @return array
     */
    public static function page($model = null, $eachFn = null, $params = [], $limit = 20)
    {
        if(is_numeric($eachFn) && is_numeric($model)){
            return parent::page($model,$eachFn);
        }

        if(is_numeric($eachFn)){
            $limit = $eachFn;
            $eachFn = null;
        }else if(is_array($eachFn)){
            $params = $eachFn;
            $eachFn = null;
        }

        if(is_callable($model)){
            $eachFn = $model;
            $model = null;
        }elseif(is_numeric($model)){
            $limit = $model;
            $model = null;
        }elseif(is_array($model)){
            $params = $model;
            $model = null;
        }

        if(is_numeric($params)){
            $limit = $params;
            $params = [];
        }

        $paginate = $model === null ? self::paginate($limit,false,['query'=>$params]) : $model->paginate($limit,false,['query'=>$params]);
        $list = is_callable($eachFn) ? $paginate->each($eachFn) : $paginate;
        $page = $list->render();
        $total = $list->total();
        return compact('list','page','total');
    }

    /**
     * 获取分页 生成where 条件和 whereOr 支持多表查询生成条件
     * @param object $model 模型对象
     * @param array $where 需要检索的数组
     * @param array $field where字段名
     * @param array $fieldOr whereOr字段名
     * @param array $fun 闭包函数
     * @param string $like 模糊查找 关键字
     * @return array
     */


    /**
     * 字符串拼接
     * @param int|array $id
     * @param string $str
     * @return string
     */
    private static function get_field($id,$str='|'){
        if(is_array($id)){
            $sql="";
            $i=0;
            foreach($id as $val){
                $i++;
                if($i<count($id)){
                    $sql.=$val.$str;
                }else{
                    $sql.=$val;
                }
            }
            return  $sql;
        }else{
            return $id;
        }
    }


    /**
     * 获取去除html去除空格去除软回车,软换行,转换过后的字符串
     * @param string $str
     * @return string
     */
    public static function HtmlToMbStr($str){
        return trim(strip_tags(str_replace(["\n","\t","\r"," ","&nbsp;"],'',htmlspecialchars_decode($str))));
    }
    /**
     * 截取中文指定字节
     * @param string $str
     * @param int $utf8len
     * @param string $chaet
     * @param string $file
     * @return string
     */
    public static function getSubstrUTf8($str,$utf8len=100,$chaet='UTF-8',$file='....'){
        if(mb_strlen($str,$chaet) > $utf8len){
            $str = mb_substr($str,0,$utf8len,$chaet).$file;
        }
        return $str;
    }
    /**
     * 获取本季度 time
     * @param int|string $time
     * @param string $ceil
     * @return array
     */
    public static function getMonth($time='',$ceil=0){
        if($ceil!=0)
            $season = ceil(date('n') /3)-$ceil;
        else
            $season = ceil(date('n') /3);
        $firstday = date('Y-m-01',mktime(0,0,0,($season - 1) *3 +1,1,date('Y')));
        $lastday = date('Y-m-t',mktime(0,0,0,$season * 3,1,date('Y')));
        return array($firstday,$lastday);
    }


    /**
     * 模型
     *
     * @param $id
     * @param $where
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function findModel($id, $where)
    {
        if (!empty($where)) {
            return self::where($where)->failException(true)->find();
        }else{
            return self::failException(true)->find($id);
        }
    }

}